/* weehttpd
* Copyright (c) 2008 Jeffery Myers
*
* This package is free software;  you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/

#include "httpd.h"
#include "textUtils.h"
#include "fileUtils.h"

#include <stdio.h>
#include <stdarg.h>
#include <sstream>
#include <algorithm>

WeeHTTPVDir::WeeHTTPVDir()
{
  serviceMimeResources = false;
  resourceRootPath = "./";

  mimeTypes[std::string("htm")]= std::string("text/html");
  mimeTypes[std::string("html")]= std::string("text/html");
  mimeTypes[std::string("txt")]= std::string("text/plain");
  mimeTypes[std::string("css")]= std::string("text/css");
  mimeTypes[std::string("png")]= std::string("image/png");
  mimeTypes[std::string("ico")]= std::string("image/vnd.microsoft.icon");
  mimeTypes[std::string("*")]= std::string("application/octet-stream");
}

WeeHTTPVDir::~WeeHTTPVDir()
{
}

void WeeHTTPVDir::addMimeType ( const std::string &extension, const std::string &type )
{
  mimeTypes[extension] = type;
}

std::string WeeHTTPVDir::getBaseURL ( void )
{
  std::string URL = "http://";
  std::string host = "localhost";
//   if (bz_getPublicAddr().size())
//     host = bz_getPublicAddr().c_str();
// 
//   // make sure it has the port
//   if ( strrchr(host.c_str(),':') == NULL )
//     host += format(":%d",bz_getPublicPort());
// 
  URL += host +"/";
  URL += getVDir();
  URL += "/";

  return URL;
}

bool WeeHTTPVDir::handleRequest(const WeeHTTPRequest &request, WeeHTTPReply &reply)
{
  if (serviceMimeResources && resourceRootPath.size() && mimeTypes.size())
  {
    // parse out the resource and see if we know what it is
    std::string ext;
    tolower(getFileExtension(request.resource),ext);

    if (ext.size())
    {
      if ( mimeTypes.find(ext) != mimeTypes.end() )
      {
	// it's one we do, try and find it
	std::string filepath = concatPaths(resourceRootPath.c_str(),request.resource.c_str());

	FILE *fp = fopen(filepath.c_str(),"rb");
	if (fp)
	{
	  char buffer[1024];
	  bool done = false;

	  while (!done)
	  {
	    size_t read = fread(buffer,1,1024,fp);
	    if (read)
	      reply.addBody(buffer,read);

	    if (read != 1024)
	      done = true;
	  }
	  fclose(fp);

	  reply.docType = WeeHTTPReply::eOther;
	  reply.otherMimeType = mimeTypes[ext];
	  reply.returnCode = WeeHTTPReply::e200OK;
	  return true;
	}
      }
    }
  }

  return generatePage(request,reply);
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
